<template>
  <div class="role-management-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>角色管理</span>
          <el-button type="primary" @click="handleAddRole">新增角色</el-button>
        </div>
      </template>
      
      <!-- 角色列表 -->
      <el-table :data="roles" style="width: 100%" v-loading="loading">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="角色名称" />
        <el-table-column prop="code" label="角色编码" />
        <el-table-column prop="description" label="角色描述" />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="状态" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status ? 'success' : 'danger'">
              {{ scope.row.status ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="280">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="success" @click="handlePermission(scope.row)">权限</el-button>
            <el-button 
              size="small" 
              :type="scope.row.status ? 'warning' : 'success'"
              @click="handleStatusChange(scope.row)"
            >
              {{ scope.row.status ? '禁用' : '启用' }}
            </el-button>
            <el-button 
              size="small" 
              type="danger" 
              @click="handleDelete(scope.row)"
              :disabled="scope.row.code === 'ADMIN' || scope.row.code === 'SUPER_ADMIN'"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 角色表单对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="isEdit ? '编辑角色' : '新增角色'" 
      width="500px"
    >
      <el-form 
        :model="roleForm" 
        :rules="rules" 
        ref="roleFormRef" 
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="code">
          <el-input 
            v-model="roleForm.code" 
            placeholder="请输入角色编码" 
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input 
            v-model="roleForm.description" 
            type="textarea" 
            placeholder="请输入角色描述"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch v-model="roleForm.status" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 权限分配对话框 -->
    <el-dialog 
      v-model="permissionVisible" 
      title="分配权限" 
      width="600px"
    >
      <div v-loading="permissionLoading">
        <el-tree
          ref="permissionTree"
          :data="permissions"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkedPermissions"
          :props="{ label: 'name' }"
        />
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="permissionVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPermission">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { roleAPI, permissionAPI } from '@/api/api'

export default {
  name: 'RoleManagement',
  setup() {
    // 数据定义
    const roles = ref([])
    const loading = ref(false)
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    
    // 表单相关
    const dialogVisible = ref(false)
    const isEdit = ref(false)
    const roleFormRef = ref(null)
    const roleForm = reactive({
      id: null,
      name: '',
      code: '',
      description: '',
      status: true
    })
    
    // 表单验证规则
    const rules = {
      name: [
        { required: true, message: '请输入角色名称', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      code: [
        { required: true, message: '请输入角色编码', trigger: 'blur' },
        { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
      ],
      description: [
        { max: 200, message: '长度不能超过 200 个字符', trigger: 'blur' }
      ]
    }
    
    // 权限相关
    const permissionVisible = ref(false)
    const permissionLoading = ref(false)
    const permissions = ref([])
    const checkedPermissions = ref([])
    const currentRoleId = ref(null)
    
    // 获取角色列表
    const fetchRoles = async () => {
      loading.value = true
      try {
        const params = {
          page: currentPage.value,
          size: pageSize.value
        }
        
        const response = await roleAPI.getRoles(params)
        
        if (response.success) {
          roles.value = response.data.list || []
          total.value = response.data.totalItems || 0
        } else {
          ElMessage.error('获取角色列表失败: ' + response.message)
        }
      } catch (error) {
        console.error('获取角色列表失败:', error)
        ElMessage.error('获取角色列表失败: ' + (error.message || '未知错误'))
      } finally {
        loading.value = false
      }
    }
    
    // 获取权限树
    const fetchPermissionTree = async () => {
      permissionLoading.value = true
      try {
        const response = await permissionAPI.getPermissionTree()
        
        if (response.success) {
          permissions.value = response.data || []
        } else {
          ElMessage.error('获取权限列表失败: ' + response.message)
        }
      } catch (error) {
        console.error('获取权限列表失败:', error)
        ElMessage.error('获取权限列表失败: ' + (error.message || '未知错误'))
      } finally {
        permissionLoading.value = false
      }
    }
    
    // 获取角色的权限
    const fetchRolePermissions = async (roleId) => {
      permissionLoading.value = true
      try {
        const response = await roleAPI.getRolePermissions(roleId)
        
        if (response.success) {
          checkedPermissions.value = response.data.map(item => item.id) || []
        } else {
          ElMessage.error('获取角色权限失败: ' + response.message)
        }
      } catch (error) {
        console.error('获取角色权限失败:', error)
        ElMessage.error('获取角色权限失败: ' + (error.message || '未知错误'))
      } finally {
        permissionLoading.value = false
      }
    }
    
    // 新增角色
    const handleAddRole = () => {
      isEdit.value = false
      resetForm()
      dialogVisible.value = true
    }
    
    // 编辑角色
    const handleEdit = (row) => {
      isEdit.value = true
      resetForm()
      
      // 复制行数据到表单
      Object.assign(roleForm, {
        id: row.id,
        name: row.name,
        code: row.code,
        description: row.description,
        status: row.status
      })
      
      dialogVisible.value = true
    }
    
    // 提交表单
    const submitForm = async () => {
      if (!roleFormRef.value) return
      
      roleFormRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const formData = { ...roleForm }
            
            const response = isEdit.value
              ? await roleAPI.updateRole(formData)
              : await roleAPI.addRole(formData)
            
            if (response.success) {
              ElMessage.success(isEdit.value ? '编辑角色成功' : '新增角色成功')
              dialogVisible.value = false
              fetchRoles()
            } else {
              ElMessage.error((isEdit.value ? '编辑角色失败: ' : '新增角色失败: ') + response.message)
            }
          } catch (error) {
            console.error(isEdit.value ? '编辑角色失败:' : '新增角色失败:', error)
            ElMessage.error((isEdit.value ? '编辑角色失败: ' : '新增角色失败: ') + (error.message || '未知错误'))
          }
        }
      })
    }
    
    // 重置表单
    const resetForm = () => {
      if (roleFormRef.value) {
        roleFormRef.value.resetFields()
      }
      
      roleForm.id = null
      roleForm.name = ''
      roleForm.code = ''
      roleForm.description = ''
      roleForm.status = true
    }
    
    // 改变角色状态
    const handleStatusChange = async (row) => {
      try {
        const response = await roleAPI.updateRoleStatus(row.id, !row.status)
        
        if (response.success) {
          ElMessage.success(`${row.status ? '禁用' : '启用'}角色成功`)
          row.status = !row.status
        } else {
          ElMessage.error(`${row.status ? '禁用' : '启用'}角色失败: ` + response.message)
        }
      } catch (error) {
        console.error(`${row.status ? '禁用' : '启用'}角色失败:`, error)
        ElMessage.error(`${row.status ? '禁用' : '启用'}角色失败: ` + (error.message || '未知错误'))
      }
    }
    
    // 删除角色
    const handleDelete = (row) => {
      ElMessageBox.confirm(
        `确定要删除角色"${row.name}"吗？`,
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      )
        .then(async () => {
          try {
            const response = await roleAPI.deleteRole(row.id)
            
            if (response.success) {
              ElMessage.success('删除角色成功')
              fetchRoles()
            } else {
              ElMessage.error('删除角色失败: ' + response.message)
            }
          } catch (error) {
            console.error('删除角色失败:', error)
            ElMessage.error('删除角色失败: ' + (error.message || '未知错误'))
          }
        })
        .catch(() => {
          ElMessage.info('已取消删除')
        })
    }
    
    // 处理分配权限
    const handlePermission = async (row) => {
      currentRoleId.value = row.id
      permissionVisible.value = true
      
      // 获取权限树
      if (permissions.value.length === 0) {
        await fetchPermissionTree()
      }
      
      // 获取角色已有权限
      await fetchRolePermissions(row.id)
    }
    
    // 提交权限分配
    const submitPermission = async () => {
      if (!currentRoleId.value) return
      
      try {
        const permissionIds = permissionTree.value?.getCheckedKeys() || []
        
        const response = await roleAPI.assignPermissions(currentRoleId.value, permissionIds)
        
        if (response.success) {
          ElMessage.success('分配权限成功')
          permissionVisible.value = false
        } else {
          ElMessage.error('分配权限失败: ' + response.message)
        }
      } catch (error) {
        console.error('分配权限失败:', error)
        ElMessage.error('分配权限失败: ' + (error.message || '未知错误'))
      }
    }
    
    // 分页相关
    const handleSizeChange = (newSize) => {
      pageSize.value = newSize
      fetchRoles()
    }
    
    const handleCurrentChange = (newPage) => {
      currentPage.value = newPage
      fetchRoles()
    }
    
    // 权限树引用
    const permissionTree = ref(null)
    
    // 生命周期钩子
    onMounted(() => {
      fetchRoles()
    })
    
    return {
      roles,
      loading,
      total,
      currentPage,
      pageSize,
      dialogVisible,
      isEdit,
      roleFormRef,
      roleForm,
      rules,
      permissionVisible,
      permissionLoading,
      permissions,
      checkedPermissions,
      permissionTree,
      handleAddRole,
      handleEdit,
      submitForm,
      handleStatusChange,
      handleDelete,
      handlePermission,
      submitPermission,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.role-management-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style> 